import { defineStore } from 'pinia'
import { userApi } from '@/services/api'
import { useAppStore } from './app'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    token: null,
    isAuthenticated: false,
    profile: null
  }),

  getters: {
    userName: (state) => {
      if (!state.user) return ''
      return state.user.first_name && state.user.last_name 
        ? `${state.user.first_name} ${state.user.last_name}`
        : state.user.username
    },
    
    userAvatar: (state) => {
      return state.user?.avatar || '/default-avatar.png'
    },

    isVerified: (state) => state.user?.is_verified || false
  },

  actions: {
    async login(credentials) {
      const appStore = useAppStore()
      
      try {
        appStore.setLoading(true)
        const response = await userApi.login(credentials)
        
        this.token = response.data.token
        this.user = response.data.user
        this.isAuthenticated = true
        
        // 保存到本地存储
        localStorage.setItem('token', this.token)
        localStorage.setItem('user', JSON.stringify(this.user))
        
        // 获取用户资料
        await this.fetchProfile()
        
        appStore.showSuccess('登录成功')
        return response.data
      } catch (error) {
        appStore.showError(error.response?.data?.detail || '登录失败')
        throw error
      } finally {
        appStore.setLoading(false)
      }
    },

    async register(userData) {
      const appStore = useAppStore()
      
      try {
        appStore.setLoading(true)
        const response = await userApi.register(userData)
        
        this.token = response.data.token
        this.user = response.data.user
        this.isAuthenticated = true
        
        // 保存到本地存储
        localStorage.setItem('token', this.token)
        localStorage.setItem('user', JSON.stringify(this.user))
        
        appStore.showSuccess('注册成功')
        return response.data
      } catch (error) {
        const message = error.response?.data?.detail || '注册失败'
        appStore.showError(message)
        throw error
      } finally {
        appStore.setLoading(false)
      }
    },

    async logout() {
      const appStore = useAppStore()
      
      try {
        if (this.token) {
          await userApi.logout()
        }
      } catch (error) {
        console.error('Logout error:', error)
      }
      
      // 清除状态和本地存储
      this.user = null
      this.token = null
      this.isAuthenticated = false
      this.profile = null
      
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      
      appStore.showSuccess('已退出登录')
    },

    async checkAuth() {
      const token = localStorage.getItem('token')
      const userStr = localStorage.getItem('user')
      
      if (token && userStr) {
        try {
          this.token = token
          this.user = JSON.parse(userStr)
          
          // 验证token是否有效
          await this.fetchProfile()
          this.isAuthenticated = true
          
          return true
        } catch (error) {
          // Token无效，清除本地存储
          this.logout()
          return false
        }
      }
      
      return false
    },

    async fetchProfile() {
      try {
        const response = await userApi.getProfile()
        this.profile = response.data
        return response.data
      } catch (error) {
        console.error('Failed to fetch profile:', error)
        throw error
      }
    },

    async updateProfile(profileData) {
      const appStore = useAppStore()
      
      try {
        appStore.setLoading(true)
        const response = await userApi.updateProfile(profileData)
        
        this.user = { ...this.user, ...response.data }
        localStorage.setItem('user', JSON.stringify(this.user))
        
        appStore.showSuccess('资料更新成功')
        return response.data
      } catch (error) {
        appStore.showError(error.response?.data?.detail || '更新失败')
        throw error
      } finally {
        appStore.setLoading(false)
      }
    },

    async changePassword(passwordData) {
      const appStore = useAppStore()
      
      try {
        appStore.setLoading(true)
        await userApi.changePassword(passwordData)
        appStore.showSuccess('密码修改成功')
      } catch (error) {
        appStore.showError(error.response?.data?.detail || '密码修改失败')
        throw error
      } finally {
        appStore.setLoading(false)
      }
    }
  }
})